package update;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class UpdateFile extends HttpServlet {
	
	private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		//HttpSession session = req.getSession(true);
		//String username = (String) session.getAttribute("username");
		
		Key entityKey = KeyFactory.stringToKey(req.getParameter("entityKey"));
		Entity file;
		try {
			file = datastore.get(entityKey);
			file.setProperty("mediaName", req.getParameter("name"));
			String type = (String) file.getProperty("contentType");
			if (type.equals("image")) { // image type files
				file.setProperty("album", req.getParameter("album"));
			} else if (type.equals("video")) { // video type files
				file.setProperty("genre", req.getParameter("genre"));
				file.setProperty("year", req.getParameter("year"));
				file.setProperty("collection", req.getParameter("collection"));
			} else if (type.equals("audio")) { // audio type files
				file.setProperty("artist", req.getParameter("artist"));
				file.setProperty("album", req.getParameter("album"));
				file.setProperty("genre", req.getParameter("genre"));
			} else { // documents type files
				file.setProperty("album", req.getParameter("album"));
			}
			
			datastore.put(file);
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.sendRedirect(req.getHeader("referer"));
	}
}
